import React, { useState } from 'react';
import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import { Button, Modal, ConfigProvider, Dropdown, Space, Tag, theme } from 'antd';
import { useRef } from 'react';
import type { TableColumnsType, TableProps } from 'antd';
import { sellerSelectModeList } from '@/../api/businessFinance/service';
const columns: ProColumns<GithubIssueItem>[] = [
    {
        dataIndex: 'index',
        valueType: 'indexBorder',
        width: 48,
    },
    {
        title: '发票名称',
        dataIndex: 'titleName',
        copyable: true,
        ellipsis: true,
        tooltip: '标题过长会自动收缩',
        formItemProps: {
            rules: [
                {
                    required: true,
                    message: '此项为必填项',
                },
            ],
        },
    },
    {
        disable: true,
        title: '复核状态',
        dataIndex: 'stateType',
        filters: true,
        onFilter: true,
        ellipsis: true,
        valueType: 'select',
        fieldProps: {
            options: [
                {
                    key: 'open',
                    text: '未解决',
                    status: 'Error',
                    label: '未解决', value: 'open'
                },
                {
                    key: 'closed',
                    text: '已解决',
                    status: 'Success',
                    label: '已解决', value: 'closed'

                },
                {
                    key: 'processing',
                    text: '解决中',
                    status: 'Processing',
                    label: '解决中', value: 'processing'
                },
            ],
        },
    },
    {
        disable: true,
        title: '标签',
        dataIndex: 'labels',
        search: false,
        renderFormItem: (_, { defaultRender }) => {
            return defaultRender(_);
        },
        render: (_, record) => (
            <Space>
                {record.labels.map(({ name, color }) => (
                    <Tag color={color} key={name}>
                        {name}
                    </Tag>
                ))}
            </Space>
        ),
    },
    {
        title: '开票时间',
        key: 'showTime',
        dataIndex: 'created_at',
        valueType: 'date',
        sorter: true,
        hideInSearch: true,
    },
    {
        title: '开票时间',
        dataIndex: 'created_at',
        valueType: 'dateRange',
        hideInTable: true,
        search: {
            transform: (value) => {
                return {
                    startTime: value[0],
                    endTime: value[1],
                };
            },
        },
    },
    {
        title: '操作',
        valueType: 'option',
        key: 'option',
        render: (text, record, _, action) => [
            // <a
            //     key="editable"
            //     onClick={() => {
            //         action?.startEditable?.(record.id);
            //     }}
            // >
            //     编辑
            // </a>,
            // <a href={record.url} target="_blank" rel="noopener noreferrer" key="view">
            //     查看
            // </a>,
            <TableDropdown
                key="actionGroup"
                onSelect={() => action?.reload()}
                menus={[
                    { key: 'copy', name: '复制' },
                    { key: 'delete', name: '删除' },
                ]}
            />,
        ],
    },
];
export interface InvoiceFormModalRef {
    showModal: () => void;
    handleCancel: () => void; // 添加这一行
}
export interface InvoiceFormModalProps {
    selectionType?: 'checkbox' | 'radio';
    onSelectedEvent(modealSelectedRows: GithubIssueItem[]):void;
    // 定义你的组件属性
}


const InvoiceFormModal = React.forwardRef<InvoiceFormModalRef, InvoiceFormModalProps>((props, ref) => {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [modealSelectedRows, setmodealSelectedRows] = useState<GithubIssueItem[]>([]);
    const actionRef = useRef<ActionType>(null);
    const selectionType = props.selectionType ?? 'checkbox';
    const themeConfig = {
        token: {
            
            borderRadius: 4,
            // 选中行背景色
            colorBgSelected: '#e6f7ff', // 浅蓝色示例
            // 选中行hover背景色
            colorBgSelectedHover: '#d1eaff',
        },
        algorithm: [theme.compactAlgorithm],
    };
    const showModal = () => {
        setIsModalOpen(true);
    };

    // 暴露showModal方法给父组件
    React.useImperativeHandle(ref, () => ({
        showModal,
        modealSelectedRows,
        handleCancel // 可选：也可以暴露关闭方法
    }));

    // 请求数据
    const fetchData = async (
        params: InvoiceInformationModealForm,
        sort: Record<string, 'ascend' | 'descend' | null>,
        filter: Record<string, (string | number)[] | null>) => {
        const response = await sellerSelectModeList(params);
        return {
            data: response.list || [],
            total: response.total || 0,
            success: true,
        };
    }
    //   确认
    const handleOk = () => {
        props.onSelectedEvent(modealSelectedRows);
        setIsModalOpen(false);
    };
    // 取消
    function handleCancel() {
        setIsModalOpen(false);
    }
    // 选择行 配置回调
    const rowSelection: TableProps<GithubIssueItem>['rowSelection'] = {
        onChange: (selectedRowKeys: React.Key[], selectedRows: GithubIssueItem[]) => {
            console.log(`当前选中: ${selectedRowKeys}`, '所以选中: ', selectedRows);
            setmodealSelectedRows(selectedRows);
        },
         // 为每一行配置复选框属性 （禁用 / 启用） （默认选中 / 不选中） 为复选框添加额外属性（如 disabled、checked 等）
        getCheckboxProps: (record: GithubIssueItem) => ({

        }),
    };
    return (
        <>
            <Modal
                title="发票信息"
                closable={{ 'aria-label': 'Custom Close Button' }}
                open={isModalOpen}
                width={1400}
                onOk={handleOk}
                onCancel={handleCancel}
            >
                <ConfigProvider theme={themeConfig}>
                    <ProTable<GithubIssueItem>
                        columns={columns}
                        rowSelection={{ type: selectionType, ...rowSelection }}
                        actionRef={actionRef}
                        cardBordered
                        request={fetchData}
                        editable={{
                            type: 'multiple',
                        }}
                        columnsState={{
                            persistenceKey: 'pro-table-singe-demos',
                            persistenceType: 'localStorage',
                            onChange(value) {
                                console.log('value: ', value);
                            },
                        }}
                        rowKey="id"
                        search={{
                            labelWidth: 'auto',
                        }}
                        options={{
                            setting: {
                                listsHeight: 400,
                            },
                        }}
                        form={{
                            // 由于配置了 transform，提交的参数与定义的不同这里需要转化一下
                            syncToUrl: (values, type) => {
                                if (type === 'get') {
                                    return {
                                        ...values,
                                        created_at: [values.startTime, values.endTime],
                                    };
                                }
                                return values;
                            },
                        }}
                        pagination={{
                            pageSize: 5,
                            onChange: (page) => console.log(page),
                        }}
                        dateFormatter="string"
                        headerTitle="发票信息"
                        toolBarRender={() => [
                        ]}
                    />
                </ConfigProvider>
            </Modal>
        </>
    );
});
// 设置组件显示名称，便于调试
InvoiceFormModal.displayName = 'InvoiceFormModal';
export default InvoiceFormModal;